package com.aboo.util;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 获取JavaBean的工具包
 * @author Yata Aboo
 *
 */
public class ContextBeanUtils {
	
	private static ApplicationContext applicationContext;

	public ContextBeanUtils() {
	}
	
	public static void initialContext(ApplicationContext context) {
		applicationContext = context;
	}

	/**
	 * 通过Spring注入的名称获取对应的JavaBean
	 * @param beanName  JavaBean注入时的名称
	 * @return  JavaBean
	 */
	public static Object getBean(String beanName) {
		return applicationContext.getBean(beanName);
	}

	/**
	 * 通过Spring注入的名称获取对应的JavaBean
	 * @param beanName  JavaBean注入时的名称
	 * @param request  HttpServletRequest对象
	 * @return  JavaBean
	 */
	public static Object getBean(String beanName, HttpServletRequest request) {
		ServletContext sc = request.getSession().getServletContext();
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sc);
		return wac.getBean(beanName);
	}

}
